package LeetCode._05_堆;

import java.util.PriorityQueue;

public class _378_有序矩阵中第K小的元素 {
    public int kthSmallest(int[][] matrix, int k) {
        if(matrix == null || matrix[0].length == 0) return 0;
        //创建一个最大堆
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1,o2) -> o2 - o1);
        for(int i=0;i<matrix.length;i++){
            for(int j = 0; j <matrix[0].length;j++){
                maxHeap.offer(matrix[i][j]);
                if(maxHeap.size()>k) maxHeap.poll();
            }
        }
        return maxHeap.peek();
    }

    public int kthSmallest2(int[][] matrix, int k) {
        if(matrix == null || matrix[0].length == 0) return 0;
        int row = matrix.length;
        int col = matrix[0].length;
        int[] nums = new int[row * col];
        int p = 0;
        for(int i=0;i<matrix.length;i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                nums[p++] = matrix[i][j];
            }
        }
        return nums[k-1];
    }

}
